package juc.threadpool.MyThreadPool;

import javafx.concurrent.Worker;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


@Slf4j(topic = "c.TestPool")
public class TestPool {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(1,
                1, TimeUnit.SECONDS, 1, (queue, task) -> {
            // 1. 死等
            queue.put(task);
            // 2) 带超时等待
//            queue.offer(task, 1500, TimeUnit.MILLISECONDS);
            // 3) 让调用者放弃任务执行
//            log.debug("放弃任务{}", task.id);
            // 4) 让调用者抛出异常
//            throw new RuntimeException("任务执行失败 " + task);
        });
        for (int i = 1; i <= 4; i++) {
            threadPool.execute(new Task(i));
        }
    }
}

/**
 * 任务类
 */
@Slf4j
class Task implements Runnable {
    int id;

    public Task(int id) {
        this.id = id;
    }

    //模拟任务执行需要耗时
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("任务{}执行完成", id);
    }
}

/**
 * 拒绝策略，
 * 函数式接口。可用lambda
 */
@FunctionalInterface
interface RejectPolicy {
    void reject(MyBlockingQueue queue, Task task);
}

/**
 * 线程池-核心
 */
@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
    // 任务队列
    private MyBlockingQueue taskQueue;

    // 线程集合
    private HashSet<Worker> workers = new HashSet<>();

    // 核心线程数
    private int coreSize;

    // 获取任务时的超时时间
    private long timeout;

    private TimeUnit timeUnit;

    private RejectPolicy rejectPolicy;

    //worker的编号
    static int no = 1;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new MyBlockingQueue(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    // 执行任务
    public void execute(Task task) {
        // 当任务数没有超过 coreSize 时，直接交给 worker 对象执行
        // 如果任务数超过 coreSize 时，加入任务队列暂存
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task, no++);
                log.debug("新增任务线程worker：{} ", worker.id);
                log.debug("worker{}获取到任务{}", worker.id, task.id);
                workers.add(worker);
                worker.start();
            } else {
//                taskQueue.put(task);
                // 1) 死等
                // 2) 带超时等待
                // 3) 让调用者放弃任务执行
                // 4) 让调用者抛出异常
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }

    /**
     * Worker:工作线程类
     */
    class Worker extends Thread {

        private Task task;
        private int id;

        public Worker(Task task, int id) {
            this.task = task;
            this.id = id;
        }

        @Override
        public void run() {
            // 执行任务
            // 1) 当 task 不为空，执行任务
            // 2) 当 task 执行完毕，再接着从任务队列获取任务并执行
//            while(task != null || (task = taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    log.debug("worker{}正在执行第 {} 个任务", this.id, task.id);
                    //执行任务
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            //如果任务执行完成，销毁线程
            synchronized (workers) {
                log.debug("worker{}被移除", this.id);
                workers.remove(this);
            }
        }
    }
}

/**
 * 阻塞队列
 */
@Slf4j(topic = "c.MyBlockingQueue")
class MyBlockingQueue {
    // 1. 任务队列
    private Deque<Task> queue = new ArrayDeque<>();

    // 2. 锁
    private ReentrantLock lock = new ReentrantLock();

    // 3. 生产者条件变量
    private Condition fullWaitSet = lock.newCondition();

    // 4. 消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    // 5. 容量
    private int capcity;

    public MyBlockingQueue(int capcity) {
        this.capcity = capcity;
    }

    // 带超时阻塞获取
    public Task poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            // 将 timeout 统一转换为 纳秒
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    // 当已经等够了10s就不等了。
                    if (nanos <= 0) {
                        return null;
                    }
                    //比如nanos一开始是10s，等了4s被唤醒，但是队列仍然是空，虚假唤醒。
                    //此时awaitNanos的返回值即为10-4=6s，接着循环就只用最多等6s
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Task t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 阻塞获取
    public Task take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Task t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 带超时时间阻塞添加
    public boolean offer(Task task, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (queue.size() == capcity) {
                try {
                    if (nanos <= 0) {
                        log.debug("任务{}不等了", task.id);
                        return false;
                    }
                    log.debug("任务{}正在等待加入任务队列", task.id);

                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("任务{}加入任务队列 ", task.id);
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    // 阻塞添加
    public void put(Task task) {
        lock.lock();
        try {
            while (queue.size() == capcity) {
                try {
                    log.debug("任务{}等待加入任务队列", task.id);
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("任务{}加入任务队列", task.id);
            queue.addLast(task);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    //拒绝策略
    public void tryPut(RejectPolicy rejectPolicy, Task task) {
        lock.lock();
        try {
            // 队列满了就执行拒绝策略
            if (queue.size() == capcity) {
                rejectPolicy.reject(this, task);
            } else {  // 有空闲
                log.debug("任务{}加入任务队列", task.id);
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }

}
